﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using umbraco.BasePages;

namespace Designit.Umb.Newsletter.Custom.usercontrols.designit.newsletter
{
    public partial class NewsletterSettings : System.Web.UI.UserControl
    {
        public bool HasMenu { get; set; }
        public bool Installing { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        private XmlDocument doc;
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!HasMenu)
            {
                Panel1.hasMenu = false;
                ButtonSave.Visible = true;
            }
            if(Width > int.MinValue)
                Panel1.Width = Width;
            if (Height > int.MinValue)
                Panel1.Height = Height;


            if (!IsPostBack)
            {
                var timeZoneId = TimeZoneInfo.Local.Id;
                //read mailsetting from config file
                doc = new XmlDocument();
                string path = @"/config/designit/newsletter/mailSettings.config";
                path = Server.MapPath(path);
                doc.Load(path);
                XmlNode xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Name']");
                txtName.Text = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Mail']");
                txtMail.Text = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='UserId']");
                txtUserID.Text = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Password']");
                txtPassword.Text = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='TimezoneId']");
                if (xnode.Attributes[1].Value.Length > 0)
                {
                    timeZoneId = xnode.Attributes[1].Value;
                }
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Smtp']");
                txtSMTP.Text = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='SmtpPort']");
                txtPort.Text = xnode.Attributes[1].Value;
                //check auth value
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='SmtpAuth']");
                if (xnode.Attributes[1].Value == "true")
                {
                    authcheck.Checked = true;
                }
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='POP3']");
                txtPOP3.Text = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='POP3port']");
                txtPopPort.Text = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Bounce']");
                txtBounce.Text = xnode.Attributes[1].Value;
                //check soft bounce value
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='SoftBounce']");
                if (xnode.Attributes[1].Value == "true")
                {
                    softBounceCheck.Checked = true;
                }
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='TestMail']");
                txttestMail.Text = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Server']");
                txtServer.Text = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Unsubscribe']");
                txtunsub.Text = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='ConfirmUnsubscribe']");
                txtconfirmUnsub.Text = xnode.Attributes[1].Value;
                XmlNodeList entryElements = doc.SelectNodes("//mailSettings/trustedSites/*");
                foreach (XmlElement element in entryElements)
                {

                    txtLocalSites.Text += element.Attributes[0].Value.ToString() + "\r\n";
                }

                TimezoneList.Items.AddRange(Bll.Helper.GetTimezoneListItems(timeZoneId));
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            ImageButton save = Panel1.Menu.NewImageButton();
            save.ImageUrl = umbraco.GlobalSettings.Path + "/images/editor/save.gif";
            save.AlternateText = "Save";
            save.Click += save_Click;
        }

        void save_Click(object sender, ImageClickEventArgs e)
        {
            Save();
        }

        protected void ButtonSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void Save()
        {
            string auth;
            if (authcheck.Checked)
            {
                auth = "true";
            }
            else
            {
                auth = "false";
            }

            string bounce;
            if (authcheck.Checked)
            {
                bounce = "true";
            }
            else
            {
                bounce = "false";
            }
            //write mailsettings to config file
            doc = new XmlDocument();
            string path = @"/config/designit/newsletter/mailSettings.config";
            path = Server.MapPath(path);
            doc.Load(path);
            XmlNode xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Name']");
            xnode.Attributes[1].Value = txtName.Text;
            xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Mail']");
            xnode.Attributes[1].Value = txtMail.Text;
            xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='UserId']");
            xnode.Attributes[1].Value = txtUserID.Text;
            //check if new password has been typed
            if (txtPassword.Text.Length > 0)
            {
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Password']");
                xnode.Attributes[1].Value = txtPassword.Text;
            }
            xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='TimezoneId']");
            xnode.Attributes[1].Value = TimezoneList.SelectedItem.Value;
            xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Smtp']");
            xnode.Attributes[1].Value = txtSMTP.Text;
            xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='SmtpPort']");
            xnode.Attributes[1].Value = txtPort.Text;
            xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='SmtpAuth']");
            xnode.Attributes[1].Value = auth;
            xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='POP3']");
            xnode.Attributes[1].Value = txtPOP3.Text;
            xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='POP3port']");
            xnode.Attributes[1].Value = txtPopPort.Text;
            xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Bounce']");
            xnode.Attributes[1].Value = txtBounce.Text;
            xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='SoftBounce']");
            xnode.Attributes[1].Value = bounce;
            xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='TestMail']");
            xnode.Attributes[1].Value = txttestMail.Text;
            xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Server']");
            xnode.Attributes[1].Value = txtServer.Text;
            xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Unsubscribe']");
            xnode.Attributes[1].Value = txtunsub.Text;
            xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='ConfirmUnsubscribe']");
            xnode.Attributes[1].Value = txtconfirmUnsub.Text;
            xnode = doc.SelectSingleNode("//mailSettings/trustedSites");
            xnode.RemoveAll();
            string[] lines = Regex.Split(txtLocalSites.Text, "\r\n");
            foreach (string s in lines)
            {
                if (s != "")
                {
                    XmlNode localNode = doc.CreateNode(XmlNodeType.Element, "trustedSite", null);
                    XmlAttribute attrib = localNode.OwnerDocument.CreateAttribute("value");
                    attrib.Value = s;
                    localNode.Attributes.Append(attrib);
                    xnode.AppendChild(localNode);

                }

            }

            doc.Save(path);

            if (!Installing)
            {
                if (this.BindingContainer is BasePage)
                    ((BasePage) this.BindingContainer).speechBubble(BasePage.speechBubbleIcon.success,
                                                                    "Mail settings saved", "");
            }
            else
            {
                if (this.BindingContainer is BasePage)
                    ((BasePage)this.BindingContainer).speechBubble(BasePage.speechBubbleIcon.success,
                                                                    "Package installed. Please log off and on again to see the section.", "");
            }


        }
    }
}